<template>
  <div class="patient-tcm-record">
    <!-- 头部区域 -->
    <div class="record-header">
      <h2><el-icon><Mug /></el-icon> 我的中药处方</h2>
      <div class="header-actions">
        <el-date-picker
            v-model="recordDate"
            type="month"
            placeholder="选择月份"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            @change="loadPrescriptionData"
            style="width: 150px;"
        />
      </div>
    </div>

    <!-- 当前用药处方 -->
    <el-card class="current-prescription">
      <template #header>
        <div class="card-header">
          <el-icon><Bell /></el-icon> 当前服用处方
        </div>
      </template>
      <div v-if="activePrescription" class="prescription-detail">
        <div class="prescription-name">{{ activePrescription.name }}</div>
        <div class="prescription-no">处方编号: {{ activePrescription.prescriptionNo }}</div>

        <div class="herbs-section">
          <div class="section-title">组成药材</div>
          <div class="herbs-list">
            <div v-for="(herb, index) in activePrescription.herbs" :key="index" class="herb-item">
              <span class="herb-name">{{ herb.name }}</span>
              <span class="herb-dosage">{{ herb.dosage }}g</span>
            </div>
          </div>
        </div>

        <div class="usage-section">
          <div class="section-title">用法用量</div>
          <div class="usage-detail">
            {{ activePrescription.usage }}，每日{{ activePrescription.dosage }}剂，
            共{{ activePrescription.duration }}天
          </div>
        </div>

        <div class="notes-section" v-if="activePrescription.notes">
          <div class="section-title">煎服方法</div>
          <div class="notes-content">{{ activePrescription.notes }}</div>
        </div>
      </div>
      <div v-else class="no-prescription">
        暂无正在服用的中药处方
      </div>
    </el-card>

    <!-- 历史处方记录 -->
    <el-card class="history-prescriptions">
      <template #header>
        <div class="card-header">
          <el-icon><Notebook /></el-icon> 历史处方记录
        </div>
      </template>
      <el-table
          :data="filteredPrescriptions"
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="prescriptionNo" label="处方编号" width="120" />
        <el-table-column prop="name" label="方剂名称" width="150" />
        <el-table-column label="主要药材" width="200">
          <template #default="{ row }">
            <div class="main-herbs">
              <span v-for="(herb, index) in row.herbs.slice(0, 3)" :key="index">
                {{ herb.name }}{{ index < 2 && index < row.herbs.length - 1 ? '、' : '' }}
              </span>
              <span v-if="row.herbs.length > 3">等{{ row.herbs.length }}味</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用法用量" width="180">
          <template #default="{ row }">
            {{ row.usage }}，{{ row.dosage }}剂/日
          </template>
        </el-table-column>
        <el-table-column label="处方时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.prescribedDate) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '进行中' ? 'success' : 'info'" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" @click="viewPrescriptionDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalPrescriptions"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 处方详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="currentPrescription?.name"
        width="50%"
    >
      <div v-if="currentPrescription" class="prescription-detail-dialog">
        <div class="detail-row">
          <span class="detail-label">处方编号:</span>
          <span class="detail-value">{{ currentPrescription.prescriptionNo }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">开具时间:</span>
          <span class="detail-value">{{ formatDate(currentPrescription.prescribedDate) }}</span>
        </div>

        <div class="herbs-section">
          <div class="section-title">组成药材</div>
          <div class="herbs-grid">
            <div v-for="(herb, index) in currentPrescription.herbs" :key="index" class="herb-item">
              <span class="herb-name">{{ herb.name }}</span>
              <span class="herb-dosage">{{ herb.dosage }}g</span>
            </div>
          </div>
        </div>

        <div class="usage-section">
          <div class="section-title">用法用量</div>
          <div class="usage-detail">
            {{ currentPrescription.usage }}，每日{{ currentPrescription.dosage }}剂，
            共{{ currentPrescription.duration }}天
          </div>
        </div>

        <div class="notes-section" v-if="currentPrescription.notes">
          <div class="section-title">煎服方法及注意事项</div>
          <div class="notes-content">{{ currentPrescription.notes }}</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printPrescription" v-if="currentPrescription?.status === '进行中'">
          打印处方
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Mug, Bell, Notebook } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

// 模拟数据
const generateMockData = () => {
  const prescriptions = [
    {
      prescriptionNo: 'TCM20230001',
      name: '四物汤',
      herbs: [
        { name: '当归', dosage: 10 },
        { name: '川芎', dosage: 8 },
        { name: '白芍', dosage: 12 },
        { name: '熟地黄', dosage: 15 }
      ],
      usage: '水煎服',
      dosage: 1,
      duration: 7,
      notes: '早晚各一剂，饭前服用。忌食生冷、辛辣食物。',
      prescribedDate: dayjs().subtract(5, 'day').format('YYYY-MM-DD'),
      status: '进行中'
    },
    {
      prescriptionNo: 'TCM20230002',
      name: '补中益气汤',
      herbs: [
        { name: '黄芪', dosage: 15 },
        { name: '人参', dosage: 6 },
        { name: '白术', dosage: 10 },
        { name: '甘草', dosage: 6 },
        { name: '当归', dosage: 9 },
        { name: '陈皮', dosage: 6 }
      ],
      usage: '水煎服',
      dosage: 2,
      duration: 14,
      notes: '每日两剂，早晚分服。服药期间避免劳累。',
      prescribedDate: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
      status: '已完成'
    },
    {
      prescriptionNo: 'TCM20230003',
      name: '桂枝汤',
      herbs: [
        { name: '桂枝', dosage: 9 },
        { name: '白芍', dosage: 9 },
        { name: '生姜', dosage: 9 },
        { name: '大枣', dosage: 12 },
        { name: '甘草', dosage: 6 }
      ],
      usage: '水煎服',
      dosage: 1,
      duration: 5,
      notes: '温服，服药后喝热粥以助药力。',
      prescribedDate: dayjs().subtract(60, 'day').format('YYYY-MM-DD'),
      status: '已完成'
    }
  ]
  return prescriptions
}

// 数据状态
const prescriptions = ref(generateMockData())
const filteredPrescriptions = ref([])
const activePrescription = computed(() => prescriptions.value.find(p => p.status === '进行中'))
const loading = ref(false)
const recordDate = ref(dayjs().format('YYYY-MM'))
const currentPage = ref(1)
const pageSize = ref(10)
const totalPrescriptions = computed(() => prescriptions.value.length)
const detailDialogVisible = ref(false)
const currentPrescription = ref(null)

// 初始化加载数据
onMounted(() => {
  filterPrescriptions()
})

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  filterPrescriptions()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  filterPrescriptions()
}

// 过滤和分页数据
const filterPrescriptions = () => {
  loading.value = true
  let result = prescriptions.value

  // 按月份筛选
  if (recordDate.value) {
    const [year, month] = recordDate.value.split('-')
    result = result.filter(p => {
      const prescribedDate = dayjs(p.prescribedDate)
      return prescribedDate.year() === parseInt(year) &&
          prescribedDate.month() + 1 === parseInt(month)
    })
  }

  filteredPrescriptions.value = result.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
  )
  loading.value = false
}

// 加载处方数据
const loadPrescriptionData = () => {
  filterPrescriptions()
}

// 查看处方详情
const viewPrescriptionDetail = (prescription) => {
  currentPrescription.value = prescription
  detailDialogVisible.value = true
}

// 打印处方
const printPrescription = () => {
  window.print()
}

// 日期格式化
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '-'
}
</script>

<style scoped>
.patient-tcm-record {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.record-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
}

.record-header .el-icon {
  margin-right: 8px;
}

.current-prescription {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  display: flex;
  align-items: center;
}

.card-header .el-icon {
  margin-right: 8px;
}

.prescription-detail {
  padding: 10px;
}

.prescription-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.prescription-no {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}

.section-title {
  font-weight: bold;
  margin: 15px 0 8px 0;
  color: #333;
  border-left: 4px solid #409EFF;
  padding-left: 8px;
}

.herbs-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
}

.herbs-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.herb-item {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.herb-name {
  font-weight: bold;
}

.herb-dosage {
  color: #666;
}

.usage-detail {
  line-height: 1.6;
}

.notes-content {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.6;
}

.no-prescription {
  text-align: center;
  padding: 30px;
  color: #999;
}

.history-prescriptions {
  margin-bottom: 20px;
}

.main-herbs {
  line-height: 1.5;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}

.prescription-detail-dialog {
  padding: 10px;
}

.detail-row {
  margin-bottom: 15px;
}

.detail-label {
  font-weight: bold;
  margin-right: 10px;
  color: #333;
}

.detail-value {
  color: #666;
}

@media (max-width: 768px) {
  .record-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .herbs-list, .herbs-grid {
    grid-template-columns: 1fr;
  }

  .prescription-detail-dialog {
    padding: 0;
  }
}
</style>
